/**
 * @file thread_utils.c
 * @brief 线程工具函数实现
 * @version 2.0
 * @date 2023-05-20
 */

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <time.h>
#include <sys/time.h>
#include "thread_utils.h"
#include "system_utils.h"

#ifdef __linux__
#include <sys/prctl.h>
#endif

int create_thread(pthread_t *thread, ThreadFunc func, void *arg, const char *name) {
    if (!thread || !func) {
        log_message(LOG_LEVEL_ERROR, "创建线程失败: 无效的参数");
        return -1;
    }
    
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    
    // 设置分离状态
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
    
    int ret = pthread_create(thread, &attr, func, arg);
    pthread_attr_destroy(&attr);
    
    if (ret != 0) {
        log_message(LOG_LEVEL_ERROR, "创建线程 '%s' 失败: %s", 
                   name ? name : "未命名", strerror(ret));
        return -1;
    }
    
    log_message(LOG_LEVEL_DEBUG, "创建线程 '%s' 成功, ID: %lu", 
               name ? name : "未命名", (unsigned long)*thread);
    
    return 0;
}

int join_thread(pthread_t thread, void **result) {
    if (thread == 0) {
        return -1;
    }
    
    int ret = pthread_join(thread, result);
    if (ret != 0) {
        log_message(LOG_LEVEL_ERROR, "等待线程结束失败: %s", strerror(ret));
        return -1;
    }
    
    log_message(LOG_LEVEL_DEBUG, "线程 %lu 已结束", (unsigned long)thread);
    return 0;
}

int cancel_thread(pthread_t thread) {
    if (thread == 0) {
        return -1;
    }
    
    int ret = pthread_cancel(thread);
    if (ret != 0) {
        log_message(LOG_LEVEL_ERROR, "取消线程失败: %s", strerror(ret));
        return -1;
    }
    
    log_message(LOG_LEVEL_DEBUG, "线程 %lu 已被取消", (unsigned long)thread);
    return 0;
}

int set_thread_cancel_state(int state) {
    int old_state;
    int ret = pthread_setcancelstate(state ? PTHREAD_CANCEL_ENABLE : PTHREAD_CANCEL_DISABLE, &old_state);
    if (ret != 0) {
        log_message(LOG_LEVEL_ERROR, "设置线程取消状态失败: %s", strerror(ret));
        return -1;
    }
    return 0;
}

int set_thread_cancel_type(int type) {
    int old_type;
    int ret = pthread_setcanceltype(type ? PTHREAD_CANCEL_ASYNCHRONOUS : PTHREAD_CANCEL_DEFERRED, &old_type);
    if (ret != 0) {
        log_message(LOG_LEVEL_ERROR, "设置线程取消类型失败: %s", strerror(ret));
        return -1;
    }
    return 0;
}

int create_mutex(pthread_mutex_t *mutex) {
    if (!mutex) {
        return -1;
    }
    
    pthread_mutexattr_t attr;
    pthread_mutexattr_init(&attr);
    pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
    
    int ret = pthread_mutex_init(mutex, &attr);
    pthread_mutexattr_destroy(&attr);
    
    if (ret != 0) {
        log_message(LOG_LEVEL_ERROR, "创建互斥锁失败: %s", strerror(ret));
        return -1;
    }
    
    return 0;
}

int destroy_mutex(pthread_mutex_t *mutex) {
    if (!mutex) {
        return -1;
    }
    
    int ret = pthread_mutex_destroy(mutex);
    if (ret != 0) {
        log_message(LOG_LEVEL_ERROR, "销毁互斥锁失败: %s", strerror(ret));
        return -1;
    }
    
    return 0;
}

int lock_mutex(pthread_mutex_t *mutex) {
    if (!mutex) {
        log_message(LOG_LEVEL_ERROR, "锁定互斥锁失败: 无效的互斥锁指针");
        return -1;
    }
    
    int ret = pthread_mutex_lock(mutex);
    if (ret != 0) {
        log_message(LOG_LEVEL_ERROR, "锁定互斥锁失败: %s", strerror(ret));
        return -1;
    }
    
    return 0;
}

int try_lock_mutex(pthread_mutex_t *mutex) {
    if (!mutex) {
        return -1;
    }
    
    int ret = pthread_mutex_trylock(mutex);
    if (ret != 0 && ret != EBUSY) {
        log_message(LOG_LEVEL_ERROR, "尝试锁定互斥锁失败: %s", strerror(ret));
        return -1;
    }
    
    return ret;  // 返回0表示成功获取锁，返回EBUSY表示锁被占用
}

int unlock_mutex(pthread_mutex_t *mutex) {
    if (!mutex) {
        return -1;
    }
    
    int ret = pthread_mutex_unlock(mutex);
    if (ret != 0) {
        log_message(LOG_LEVEL_ERROR, "解锁互斥锁失败: %s", strerror(ret));
        return -1;
    }
    
    return 0;
}

int create_cond(pthread_cond_t *cond) {
    if (!cond) {
        return -1;
    }
    
    int ret = pthread_cond_init(cond, NULL);
    if (ret != 0) {
        log_message(LOG_LEVEL_ERROR, "创建条件变量失败: %s", strerror(ret));
        return -1;
    }
    
    return 0;
}

int destroy_cond(pthread_cond_t *cond) {
    if (!cond) {
        return -1;
    }
    
    int ret = pthread_cond_destroy(cond);
    if (ret != 0) {
        log_message(LOG_LEVEL_ERROR, "销毁条件变量失败: %s", strerror(ret));
        return -1;
    }
    
    return 0;
}

int wait_cond(pthread_cond_t *cond, pthread_mutex_t *mutex) {
    if (!cond || !mutex) {
        return -1;
    }
    
    int ret = pthread_cond_wait(cond, mutex);
    if (ret != 0) {
        log_message(LOG_LEVEL_ERROR, "等待条件变量失败: %s", strerror(ret));
        return -1;
    }
    
    return 0;
}

int wait_cond_timeout(pthread_cond_t *cond, pthread_mutex_t *mutex, long timeout_ms) {
    if (!cond || !mutex || timeout_ms < 0) {
        return -1;
    }
    
    struct timespec ts;
    clock_gettime(CLOCK_REALTIME, &ts);
    
    ts.tv_sec += timeout_ms / 1000;
    ts.tv_nsec += (timeout_ms % 1000) * 1000000;
    
    // 处理溢出
    if (ts.tv_nsec >= 1000000000) {
        ts.tv_sec += 1;
        ts.tv_nsec -= 1000000000;
    }
    
    int ret = pthread_cond_timedwait(cond, mutex, &ts);
    if (ret != 0 && ret != ETIMEDOUT) {
        log_message(LOG_LEVEL_ERROR, "等待条件变量(带超时)失败: %s", strerror(ret));
        return -1;
    }
    
    return ret;  // 返回0表示条件已满足，返回ETIMEDOUT表示超时
}

int signal_cond(pthread_cond_t *cond) {
    if (!cond) {
        return -1;
    }
    
    int ret = pthread_cond_signal(cond);
    if (ret != 0) {
        log_message(LOG_LEVEL_ERROR, "发送条件变量信号失败: %s", strerror(ret));
        return -1;
    }
    
    return 0;
}

int broadcast_cond(pthread_cond_t *cond) {
    if (!cond) {
        return -1;
    }
    
    int ret = pthread_cond_broadcast(cond);
    if (ret != 0) {
        log_message(LOG_LEVEL_ERROR, "广播条件变量信号失败: %s", strerror(ret));
        return -1;
    }
    
    return 0;
}

void thread_sleep(unsigned long ms) {
    struct timespec ts;
    ts.tv_sec = ms / 1000;
    ts.tv_nsec = (ms % 1000) * 1000000;
    nanosleep(&ts, NULL);
}

// ========================= 以下是整合自global_mutex.c的内容 =========================

// 引用全局变量
extern float g_current_ice_thickness;
extern float g_previous_ice_thickness;

// 全局互斥锁数组
static pthread_mutex_t g_mutexes[MUTEX_COUNT];
static int g_mutexes_initialized = 0;

// 互斥锁名称，用于调试日志
static const char* mutex_names[MUTEX_COUNT] __attribute__((unused)) = {
    "覆冰厚度",
    "融合数据",
    "配置数据",
    "视觉数据",
    "立体视觉数据",
    "传感器数据",
    "文件访问",
    "数据访问",
    "网络访问"
};

/**
 * @brief 初始化全局互斥锁系统
 * 
 * @return int 成功返回0，失败返回非0
 */
int init_global_mutex(void) {
    if (g_mutexes_initialized) {
        log_message(LOG_LEVEL_WARNING, "全局互斥锁系统已经初始化");
        return 0;
    }

    for (int i = 0; i < MUTEX_COUNT; i++) {
        pthread_mutex_init(&g_mutexes[i], NULL);
    }
    
    g_mutexes_initialized = 1;
    log_message(LOG_LEVEL_DEBUG, "全局互斥锁系统初始化成功");
    return 0;
}

/**
 * @brief 清理全局互斥锁系统
 */
void cleanup_global_mutex(void) {
    if (!g_mutexes_initialized) {
        return;
    }

    for (int i = 0; i < MUTEX_COUNT; i++) {
        pthread_mutex_destroy(&g_mutexes[i]);
    }
    
    g_mutexes_initialized = 0;
    log_message(LOG_LEVEL_DEBUG, "全局互斥锁系统已清理");
}

/**
 * @brief 锁定指定类型的互斥锁
 * 
 * @param type 互斥锁类型
 * @return int 成功返回0，失败返回非0
 */
int lock_global_mutex(MutexType type) {
    if (type >= MUTEX_COUNT || !g_mutexes_initialized) {
        log_message(LOG_LEVEL_ERROR, "错误：尝试锁定无效的互斥锁类型 %d", type);
        return -1;
    }
    
    pthread_mutex_lock(&g_mutexes[type]);
    return 0;
}

/**
 * @brief 尝试锁定指定类型的互斥锁，非阻塞
 * 
 * @param type 互斥锁类型
 * @return int 成功锁定返回0，锁已被占用返回EBUSY，其他错误返回对应错误码
 */
int try_lock_global_mutex(MutexType type) {
    if (type >= MUTEX_COUNT || !g_mutexes_initialized) {
        log_message(LOG_LEVEL_ERROR, "错误：尝试锁定无效的互斥锁类型 %d", type);
        return -1;
    }
    
    return (pthread_mutex_trylock(&g_mutexes[type]) == 0) ? 0 : EBUSY;
}

/**
 * @brief 解锁指定类型的互斥锁
 * 
 * @param type 互斥锁类型
 * @return int 成功返回0，失败返回非0
 */
int unlock_global_mutex(MutexType type) {
    if (type >= MUTEX_COUNT || !g_mutexes_initialized) {
        log_message(LOG_LEVEL_ERROR, "错误：尝试解锁无效的互斥锁类型 %d", type);
        return -1;
    }
    
    pthread_mutex_unlock(&g_mutexes[type]);
    return 0;
}

/**
 * @brief 安全的设置当前覆冰厚度
 * 
 * @param thickness 覆冰厚度值(mm)
 */
void set_ice_thickness_safe(float thickness) {
    lock_global_mutex(MUTEX_ICE_THICKNESS);
    g_current_ice_thickness = thickness;
    unlock_global_mutex(MUTEX_ICE_THICKNESS);
}

/**
 * @brief 安全的获取当前覆冰厚度
 * 
 * @return float 当前覆冰厚度值(mm)
 */
float get_ice_thickness_safe(void) {
    float thickness;
    lock_global_mutex(MUTEX_ICE_THICKNESS);
    thickness = g_current_ice_thickness;
    unlock_global_mutex(MUTEX_ICE_THICKNESS);
    return thickness;
}

/**
 * @brief 安全的设置上一次覆冰厚度
 * 
 * @param thickness 上一次覆冰厚度值(mm)
 */
void set_previous_ice_thickness_safe(float thickness) {
    lock_global_mutex(MUTEX_ICE_THICKNESS);
    g_previous_ice_thickness = thickness;
    unlock_global_mutex(MUTEX_ICE_THICKNESS);
}

/**
 * @brief 安全的获取上一次覆冰厚度
 * 
 * @return float 上一次覆冰厚度值(mm)
 */
float get_previous_ice_thickness_safe(void) {
    float thickness;
    lock_global_mutex(MUTEX_ICE_THICKNESS);
    thickness = g_previous_ice_thickness;
    unlock_global_mutex(MUTEX_ICE_THICKNESS);
    return thickness;
}

/**
 * @brief 安全地更新当前和上一次覆冰厚度（原子操作）
 * 
 * @param current_thickness 当前覆冰厚度值(mm)
 */
void update_ice_thickness_safe(float current_thickness) {
    lock_global_mutex(MUTEX_ICE_THICKNESS);
    g_previous_ice_thickness = g_current_ice_thickness;
    g_current_ice_thickness = current_thickness;
    unlock_global_mutex(MUTEX_ICE_THICKNESS);
}

/**
 * @brief 设置当前线程的名称
 * 
 * @param name 线程名称
 * @return int 成功返回0，失败返回非0
 */
int set_thread_name(const char *name) {
    if (!name) {
        return -1;
    }
    
#ifdef __linux__
    // Linux系统使用prctl设置线程名称
    return prctl(PR_SET_NAME, name, 0, 0, 0);
#else
    // 其他平台可能需要不同的实现
    (void)name; // 避免未使用参数的警告
    return 0;
#endif
} 